package org.yunfeng.manage.http.oss;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.Random;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class OssClient {
	@Resource
	OssConfig ossConfig;

	public String saveFile(MultipartFile uploadFile) throws IllegalStateException, IOException {
		String path = generateFilePath();
		String fileName = generateFileName(uploadFile.getOriginalFilename());
		//回显路径
		String url = ossConfig.getImageBaseUrl() + OssContants.IMAGE + path + fileName;
		//本地保存路径
		String repositoryPath =	ossConfig.getRepositoryPath() + OssContants.IMAGE + path;
		//生成本地文件夹
		File dir = new File(repositoryPath);
		if(!dir.exists()){ dir.mkdirs(); }
		
		//保存到本地
		uploadFile.transferTo(new File(repositoryPath+fileName));
		return url;
	}
	
	/**
	 * 定义文件名: 前缀 + 3位随机值 + 图片文件后缀
	 */
	private String generateFileName(String fileName) {
		String prefix = generateFileNamePrefix();
		String suffix = fileName.substring((fileName.lastIndexOf(".")));
		Random random = new Random();
		fileName = prefix + random.nextInt(999) + suffix;
		
		return fileName;
	}
	
	/** 生成文件名前缀: 当前时间的yyyyMMddHHmmssSSSS格式*/
	private String generateFileNamePrefix() {
		//FIXME 此方法有线程安全问题,应该用JDK1.8新API改写
		return new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
	}

	/**
	 * 本地文件夹路径 : 按当前年/月/日/分隔设置
	 */
	private String generateFilePath() {
		LocalDate now = LocalDate.now();
		String filePath = now.getYear() 
				+ File.separator + now.getMonthValue() 
				+ File.separator + now.getDayOfMonth()
				+ File.separator;
		return filePath;
	}
}
